import React, { useLayoutEffect, useState } from 'react';
import {
  ScrollView,
  exitMiniProgram,
  hideMenuButton,
  navigateTo,
  Text,
  publishDps,
  vibrateShort,
} from '@ray-js/ray';
import clsx from 'clsx';

import { useDevice, useProps, useStructuredActions, useStructuredProps } from '@ray-js/panel-sdk';
import { getCachedSystemInfo } from '@/api/getCachedSystemInfo';
import { NavBar, Slider } from '@ray-js/smart-ui';
import _ from 'lodash';

import { Image, View } from '@/components';

import LampColorSlider from '@ray-js/lamp-color-slider';
import styles from './index.module.less';
import res from '../../../public/image';

const { safeArea } = getCachedSystemInfo();

const { height } = safeArea;

export function Home() {
  const deviceName = useDevice(d => d.devInfo.name);
  const deviceId = useDevice(d => d.devInfo.devId);
  const groupId = useDevice(d => d.devInfo.groupId);

  const [tab, setTab] = useState<'home' | 'other'>('home');

  const [scrollEnabled, setScrollEnabled] = useState(false);

  const dpStructuredActions = useStructuredActions();
  const colour = useStructuredProps(props => props.colour_data);

  useLayoutEffect(() => {
    hideMenuButton();
  }, []);

  const {
    work_mode_sofa: workModeSofa,
    shoulder_vibration: shoulderVibration,
    lumbar_vibration: lumbarVibration,
    hip_vibration: hipVibration,
    thigh_vibration: thighVibration,
    switch_led: switchLed,
    volume_set: volumeSet,
    bass_set: bassSet,
    vibration_set: vibrationSet,
    treble_set: trebleSet,
    play_set: playSet,
    work_number: workNumber,
    vibration_mode: vibrationMode,
    jilian,
  } = useProps();

  const decodeVibrationMode = (mode: string) => {
    if (vibrationMode.length !== 4) {
      return {
        showShoulder: true,
        showLumbar: true,
        showHip: true,
        showThigh: true,
      };
    } else {
      return {
        showShoulder: vibrationMode[0] === '1',
        showLumbar: vibrationMode[1] === '1',
        showThigh: vibrationMode[2] === '1',
        showHip: vibrationMode[3] === '1',
      };
    }
  };

  const { showShoulder, showLumbar, showHip, showThigh } = decodeVibrationMode(vibrationMode);

  const onClickLeft = () => {
    exitMiniProgram();
  };

  const renderHome = () => {
    console.log(`🚀 ~ workModeSofa:`, workModeSofa);
    return (
      <View className={styles.homeBox} key="homeBox">
        <View className={styles.logoBox}>
          <Image src={res.logoWithLight} className={styles.logo} />
        </View>

        <View className={styles.content}>
          {workNumber > 0 ? (
            <View className={styles.modeBox}>
              {new Array(workNumber).fill(0).map((_, index) => {
                const isActive = workModeSofa === `mode${index + 1}`;
                return (
                  <View
                    key={`mode${index}`}
                    className={clsx(
                      isActive ? styles.modeItemActive : '',
                      styles.modeItem,
                      styles[`modeItem${workNumber}`]
                    )}
                    onClick={() => {
                      publishDps({
                        work_mode_sofa: `mode${index + 1}`,
                      });
                      vibrateShort({ type: 'light' });
                    }}
                  >
                    <Text>模式{index + 1}</Text>
                  </View>
                );
              })}
            </View>
          ) : null}

          <View className={styles.sliderBox}>
            {[
              {
                title: '肩膀震动',
                value: shoulderVibration,
                show: showShoulder,
                onAfterChange: value => {
                  publishDps({
                    shoulder_vibration: value,
                  });
                },
              },
              {
                title: '腰部震动',
                value: lumbarVibration,
                show: showLumbar,
                onAfterChange: value => {
                  publishDps({
                    lumbar_vibration: value,
                  });
                },
              },
              {
                title: '臀部震动',
                value: hipVibration,
                show: showHip,
                onAfterChange: value => {
                  publishDps({
                    hip_vibration: value,
                  });
                },
              },
              {
                title: '大腿震动',
                value: thighVibration,
                show: showThigh,
                onAfterChange: value => {
                  publishDps({
                    thigh_vibration: value,
                  });
                },
              },
            ]
              .filter(item => item.show)
              .map(item => (
                <View className={styles.sliderItem} key={item}>
                  <View className={styles.sliderTitle}>
                    <Text>{item.title}</Text>
                  </View>
                  <View>
                    <Slider
                      enableTouch
                      maxTrackHeight="16rpx"
                      minTrackHeight="16rpx"
                      max={100}
                      min={0}
                      step={1}
                      value={item.value}
                      maxTrackColor="#CCD7E0"
                      minTrackColor="#3EAEFF"
                      thumbStyle={{
                        width: '22rpx',
                        height: '42rpx',
                        borderRadius: '22rpx',
                        background: '#fff',
                        border: '2rpx solid #3EAEFF',
                      }}
                      onAfterChange={value => {
                        item.onAfterChange?.(value);
                      }}
                      style={{
                        width: `490rpx`,
                      }}
                    />
                  </View>
                </View>
              ))}
          </View>
          <View className={styles.sliderBox}>
            {[
              {
                code: 'bright_value',
                title: '亮度',
                value: colour.value,
                max: 1000,
                min: 0,
                onAfterChange: value => {
                  dpStructuredActions.colour_data.set({
                    ...colour,
                    value,
                  });
                },
              },
              {
                code: 'color',
                title: 'RGB灯光',
                value: colour.hue,
                max: 360,
                min: 0,
                onAfterChange: value => {
                  dpStructuredActions.colour_data.set({
                    ...colour,
                    hue: value,
                  });
                },
              },
            ].map(item => (
              <View className={styles.sliderItem} key={item}>
                <View className={styles.sliderTitle}>
                  <Text>{item.title}</Text>
                </View>
                <View>
                  {item.code === 'color' ? (
                    <LampColorSlider
                      value={item.value}
                      onTouchEnd={item.onAfterChange}
                      trackStyle={{
                        height: '16rpx',
                        width: '490rpx',
                      }}
                      thumbStyle={{
                        width: '22rpx',
                        height: '42rpx',
                        borderRadius: '22rpx',
                        background: '#fff',
                        border: '2rpx solid #3EAEFF',
                      }}
                    />
                  ) : (
                    <Slider
                      enableTouch
                      maxTrackHeight="16rpx"
                      minTrackHeight="16rpx"
                      max={item.max}
                      min={item.min}
                      step={10}
                      value={item.value}
                      maxTrackColor="#CCD7E0"
                      minTrackColor="#3EAEFF"
                      thumbStyle={{
                        width: '22rpx',
                        height: '42rpx',
                        borderRadius: '22rpx',
                        background: '#fff',
                        border: '2rpx solid #3EAEFF',
                      }}
                      onAfterChange={item.onAfterChange}
                      style={{
                        width: `490rpx`,
                      }}
                    />
                  )}
                </View>
              </View>
            ))}
          </View>

          <View className={styles.btnContainer}>
            <View className={styles.switchLedBox}>
              <Image
                src={switchLed ? res.powerOn : res.powerOff}
                className={styles.switchLed}
                onClick={() => {
                  // setSwitchLed(!switchLed);
                  publishDps({
                    switch_led: !switchLed,
                  });
                  vibrateShort({
                    type: 'light',
                  });
                }}
              />
            </View>
            <View className={styles.jilian}>
              <Image
                src={jilian ? res.jilian : res.jilianOff}
                className={styles.jilianIcon}
                onClick={() => {
                  // setSwitchLed(!switchLed);
                  publishDps({
                    jilian: !jilian,
                  });
                  vibrateShort({
                    type: 'light',
                  });
                }}
              />
            </View>
          </View>
        </View>
      </View>
    );
  };

  const renderOthers = () => {
    return (
      <View className={styles.homeBox} key="ohterBox">
        <View className={styles.yodeeBox}>
          <Image src={res.logo} className={styles.yodee} />
        </View>
        <View className={styles.ohterBox}>
          <View className={styles.voiceBox}>
            <View className={styles.otherSliderBox}>
              <Image src={res.voice} className={styles.voiceIcon} />
              <Slider
                enableTouch
                maxTrackHeight="16rpx"
                minTrackHeight="16rpx"
                max={100}
                min={0}
                step={1}
                value={volumeSet}
                maxTrackColor="#CCD7E0"
                minTrackColor="#3EAEFF"
                thumbStyle={{
                  width: '22rpx',
                  height: '42rpx',
                  borderRadius: '22rpx',
                  background: '#fff',
                  border: '2rpx solid #3EAEFF',
                }}
                onAfterChange={value => {
                  // item.onAfterChange?.(value);
                  publishDps({
                    volume_set: value,
                  });
                }}
                style={{
                  width: `550rpx`,
                }}
              />
            </View>
          </View>

          <View className={styles.sliderBox}>
            {[
              {
                title: '高音',
                value: trebleSet,
                onAfterChange: value => {
                  publishDps({
                    treble_set: value,
                  });
                },
              },
              {
                title: '低音',
                value: bassSet,
                onAfterChange: value => {
                  publishDps({
                    bass_set: value,
                  });
                },
              },
              {
                title: '震动',
                value: vibrationSet,
                onAfterChange: value => {
                  publishDps({
                    vibration_set: value,
                  });
                },
              },
            ].map(item => (
              <View className={styles.ohterSliderItem} key={item.title}>
                <View className={styles.sliderTitle}>
                  <Text>{item.title}</Text>
                </View>
                <View>
                  <Slider
                    enableTouch
                    maxTrackHeight="16rpx"
                    minTrackHeight="16rpx"
                    max={100}
                    min={0}
                    step={1}
                    value={item.value}
                    maxTrackColor="#CCD7E0"
                    minTrackColor="#3EAEFF"
                    thumbStyle={{
                      width: '22rpx',
                      height: '42rpx',
                      borderRadius: '22rpx',
                      background: '#fff',
                      border: '2rpx solid #3EAEFF',
                    }}
                    onAfterChange={value => {
                      item.onAfterChange?.(value);
                    }}
                    style={{
                      width: `550rpx`,
                    }}
                  />
                </View>
              </View>
            ))}
          </View>
          <View className={styles.controlBox}>
            <Image
              src={res.prev}
              className={styles.controlIcon}
              onClick={() => {
                publishDps({
                  play_set: 'up',
                });
                vibrateShort({
                  type: 'light',
                });
              }}
            />
            <Image
              src={playSet === 'pause' ? res.stop : res.play}
              className={styles.controlCenterIcon}
              onClick={() => {
                publishDps({
                  play_set: playSet === 'pause' ? 'play' : 'pause',
                });
                vibrateShort({
                  type: 'light',
                });
              }}
            />
            <Image
              src={res.next}
              className={styles.controlIcon}
              onClick={() => {
                publishDps({
                  play_set: 'down',
                });
                vibrateShort({
                  type: 'light',
                });
              }}
            />
          </View>
        </View>
      </View>
    );
  };

  return (
    <View className={styles.view}>
      <NavBar
        title={deviceName || ''}
        className={styles.navBar}
        leftArrow
        onClickLeft={onClickLeft}
        slot={{
          right: (
            <View className={styles.tabTopIconWrap}>
              <Image
                onClick={() => {
                  const jumpUrl = `functional://settings/detail?deviceId=${deviceId ||
                    ''}&groupId=${groupId || ''}`;
                  navigateTo({
                    url: jumpUrl,
                  });
                }}
                src={res.detail}
              />
            </View>
          ),
        }}
        customClass={styles.borBot}
      />
      <ScrollView
        scrollY={scrollEnabled}
        refresherTriggered
        className={clsx(styles.slideUpContent)}
        style={{
          height: `calc(${height}px - 100px)`,
        }}
      >
        {tab === 'home' ? renderHome() : renderOthers()}
      </ScrollView>

      <View className={styles.bottomBar}>
        {[
          {
            code: 'home',
            image: res.home,
            activeImage: res.homeActive,
            title: '首页',
          },
          {
            code: 'other',
            image: res.others,
            activeImage: res.ohterActive,

            title: '其他',
          },
        ].map(item => (
          <View
            className={clsx(styles.tabItem, tab === item.code && styles.tabItemActive)}
            key={item.code}
            onClick={() => {
              setTab(item.code);
            }}
          >
            <Image
              src={tab === item.code ? item.activeImage : item.image}
              className={styles.tabImage}
            />
            <Text>{item.title}</Text>
          </View>
        ))}
      </View>
    </View>
  );
}

export default Home;
